package com.acooly.module.openapi.client.provider.bosc.marshall;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.acooly.core.utils.net.HttpResult;
import com.acooly.module.openapi.client.api.exception.ApiClientException;
import com.acooly.module.openapi.client.api.marshal.ApiUnmarshal;
import com.acooly.module.openapi.client.api.util.Jsons;
import com.acooly.module.openapi.client.provider.bosc.BoscMessageFactory;
import com.acooly.module.openapi.client.provider.bosc.domain.BoscResponseDomain;
import com.alibaba.fastjson.JSONObject;

@Service
public class BoscResponseUnmarshall extends BoscMarshallSupport
		implements ApiUnmarshal<BoscResponseDomain, HttpResult> {

	@Autowired
	private BoscMessageFactory boscMessageFactory;

	// ? 未验证签名，安全隐患！！！
	@Override
	public BoscResponseDomain unmarshal(HttpResult message, String serviceKey) {
		try {
			BoscResponseDomain response = (BoscResponseDomain) boscMessageFactory.getResponse(serviceKey);
			String json = message.getBody();
			if (-1 != json.indexOf("data")) {
				String data = JSONObject.parseObject(json).get("data").toString();
				try {
					response = Jsons.parse(data, response.getClass());
				} catch (Exception e) {
					StringBuffer sb = new StringBuffer("{\"data\":\"");
					sb.append(data);
					sb.append("\"}");
					response = Jsons.parse(sb.toString(), response.getClass());
				}
				response.setResultCode(JSONObject.parseObject(json).get("resultCode").toString());
				response.setResultDesc(JSONObject.parseObject(json).get("resultDesc").toString());
			} else {
				response = Jsons.parse(json, response.getClass());
			}
			response.setService(serviceKey);
			return response;
		} catch (Exception e) {
			throw new ApiClientException(e.getMessage());
		}
	}

}
